import { Bus, CONN_STATUS, PING } from "./Bus";
import { IBroadcast } from "./IBroadcast";

export const PING_INTERVAL_TIME = 5000;

export class PingChainBroadcast extends IBroadcast {
    tid = 0;
    cur = 0;

    subscribe(): void {
        this.sendPing();
        this.tid = window.setInterval(() => {
            this.sendPing();
        }, PING_INTERVAL_TIME);
    }

    unSubscribe(): void {
        window.clearInterval(this.tid);
    }

    sendPing() {
        this.cur = Date.now();

        if (this.chainSocket.readyState == 1) {
            this.chainSocket.send("ping");
        } else {
            console.log("socket 已经关闭");
            this.unSubscribe();
            // Bus.emit(PING, PING_INTERVAL_TIME);
            // Bus.emit(CONN_STATUS, 3);
        }
    }

    handle(data?: any): void {
        // Bus.emit(PING, Date.now() - this.cur);
    }
}
